package it.com.chen.movieReleasesDB;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Calendar;
import java.util.HashMap;

public abstract class FileDBSaver {

	public static void save(HashMap<Integer, DBEntry> db) {

		String filePath = null;
		try {
			// get the path of the input file
			File directory = new File(".");
			String canonicalPath = "";
			canonicalPath = directory.getCanonicalPath();
			filePath = canonicalPath + "/db/data.dat";

			File configFile = new File(filePath);
			if (configFile.exists()) {
				configFile.delete();
			}

			FileWriter fstream = null;
			fstream = new FileWriter(filePath);

			BufferedWriter out = new BufferedWriter(fstream);

			Calendar today = Calendar.getInstance();

			String commentRow = "# last time of update (date, month, year)";

			String lastUpdateRow = "last_update" + " "
					+ today.get(Calendar.DAY_OF_MONTH) + " "
					+ today.get(Calendar.MONTH) + " "
					+ today.get(Calendar.MONTH);

			out.write(commentRow);
			out.newLine();
			out.write(lastUpdateRow);
			out.newLine();

			for (int i = 0; i < db.size(); i++) {
				DBEntry entry = db.get(i);
				out.write(entry.getMovieTitle() + "\t|\t"
						+ entry.getReleaseDate() + "\t|\t"
						+ entry.getReleaseMonth() + "\t|\t"
						+ entry.getReleaseYear() + "\t|\t"
						+ entry.getDescriptionUrl() + "\n");
			}

			out.close();
			fstream.close();

			System.out.println("\nSaving the db file \"" + filePath + "\"");

		} catch (Exception e) {
			System.err.println(e);
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Calendar lastUpdate = Calendar.getInstance();
		lastUpdate.set(2012, 8, 16);
		HashMap<Integer, DBEntry> db = new HashMap<>();
		db = OnlineDBReader.populateDB("september", 2012, db, lastUpdate);
		System.out.println("\n");
		MovieListPrinter.print(db);
		save(db);
	}

}
